package Day2025_01_18;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * 基于UPD的回显服务器
 *
 */

public class UDPEchoServer {
    // 声明一个提供UPD服务的对象
    private DatagramSocket socket;

    // 通过构造方法指定服务器的端口号
    public UDPEchoServer (int port) throws SocketException {
        // 校验端口号
        if (port < 1024 || port > 65535) {
            throw new BindException("端口号必须在1025 ~ 65535之间.");
        }
        // 初始化UPD服务对象
        this.socket = new DatagramSocket(port);
    }

    /**
     * 处理用户请求
     */
    public void start () throws IOException {
        System.out.println("服务器已启动.");
        // 循环处理用户请求
        while (true) {
            // 1.使用DatagramPacket来接收用户发来的数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            // 2.接收数据
            socket.receive(requestPacket);
            // 3.解析收到的数据
            String request = new String(requestPacket.getData(),
                    0, requestPacket.getLength(), "UTF-8");
            // 4.通过请求计算响应
            String response = process(request);
            // 5.使用DatagramPacket封装相应的数据
            DatagramPacket responsePacket = new DatagramPacket(
                    response.getBytes(StandardCharsets.UTF_8), 0,
                    response.getBytes().length, requestPacket.getSocketAddress());
            // 6.发送响应
            socket.send(responsePacket);
            // 7.打印日志
            System.out.printf("[%s,%d] request = %s, response = %s\n",
                    requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }
    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer server = new UDPEchoServer(8888);
        server.start();
    }
}
